#include "native_db.h"
#include <database/rdb/relational_store_error_code.h>
static void ReorderIds(OH_Rdb_Store *store_);
// 初始化数据库
OH_Rdb_Store *InitRdbStore(const std::string &sandboxPath, const std::string &bundleName) {
    // 创建OH_Rdb_Config对象
    OH_Rdb_Config config;
    // 该路径为应用沙箱路径
    config.dataBaseDir = sandboxPath.c_str();
    // 数据库文件名
    config.storeName = "user.db";
    // 应用包名
    config.bundleName = bundleName.c_str();
    // 应用模块名
    config.moduleName = "entry";
    // 数据库文件安全等级
    config.securityLevel = OH_Rdb_SecurityLevel::S1;
    // 数据库是否加密
    config.isEncrypt = false;
    // config所占内存大小
    config.selfSize = sizeof(OH_Rdb_Config);
    // 数据库文件存放的安全区域
    config.area = RDB_SECURITY_AREA_EL1;

    int errCode = 0;
    // 获取OH_Rdb_Store实例
    OH_Rdb_Store *store_ = OH_Rdb_GetOrOpen(&config, &errCode);
    if (store_) {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_GetOrOpen success");
        // 创建数据表SQL
        char createTableSql[] = "CREATE TABLE IF NOT EXISTS users ("
                                "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                                "name TEXT NOT NULL,"
                                "age INTEGER);";
        // 执行建表语句
        int rowId = OH_Rdb_Execute(store_, createTableSql);
        if (rowId != RDB_OK) {
            OH_LOG_INFO(LOG_APP, "OH_Rdb_Execute error");
        }
        OH_LOG_INFO(LOG_APP, "OH_Rdb_Execute success");

        // 检查数据库是否为空，如果为空则重新排序ID
        std::vector<User> users = QueryUsers(store_);
        if (users.empty()) {
            ReorderIds(store_);
        }
        return store_;
    } else {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_GetOrOpen error :%{public}d", errCode);
        return nullptr;
    }
}

// 当数据库为空时，重新排序 id
static void ReorderIds(OH_Rdb_Store *store_) {
    // 重置自增id
    char resetSql[] = "DELETE FROM sqlite_sequence WHERE name = 'users';";
    OH_Rdb_Execute(store_, resetSql);
}

// 插入用户数据
bool InsertUser(OH_Rdb_Store *store_, const std::string &name, int age) {
    // 检查数据库是否为空，如果为空则重新排序ID
    std::vector<User> users = QueryUsers(store_);
    if (users.empty()) {
        ReorderIds(store_);
    }

    OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket();
    // 构建ValuesBucket
    valueBucket->putText(valueBucket, "name", name.c_str());
    valueBucket->putInt64(valueBucket, "age", age);

    // 执行插入操作
    int rowId = OH_Rdb_Insert(store_, "users", valueBucket);
    if (rowId != RDB_ERR) {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_Insert success rowId: %{public}d", rowId);
        valueBucket->destroy(valueBucket);
        return true;
    } else {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_Insert error %{public}d", rowId);
        return false;
    }
}

// 删除用户数据
bool DeleteUser(OH_Rdb_Store *store_, int64_t id) {
    OH_Predicates *predicates = OH_Rdb_CreatePredicates("users");
    OH_VObject *valueObject = OH_Rdb_CreateValueObject();
    valueObject->putInt64(valueObject, &id, 1);
    predicates->equalTo(predicates, "id", valueObject);
    int deleteRows = OH_Rdb_Delete(store_, predicates);
    valueObject->destroy(valueObject);
    predicates->destroy(predicates);
    if (deleteRows != 0) {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_Delete success deleteRows: %{public}d", deleteRows);
        std::vector<User> users = QueryUsers(store_);
        if (users.empty()) {
            ReorderIds(store_);
        }
        return true;
    } else {
        OH_LOG_INFO(LOG_APP, "OH_Rdb_Delete error %{public}d", deleteRows);
        return false;
    }
}

// 查询用户数据
std::vector<User> QueryUsers(OH_Rdb_Store *store_) {
    OH_Predicates *predicates = OH_Rdb_CreatePredicates("users");
    // 构建查询条件
    const char *columnNames[] = {"id", "name", "age"};
    int len = sizeof(columnNames) / sizeof(columnNames[0]);
    OH_Cursor *cursor = OH_Rdb_Query(store_, predicates, columnNames, len);
    int columnCount = 0;
    cursor->getColumnCount(cursor, &columnCount);

    std::vector<User> users;
    User user;
    while (cursor->goToNextRow(cursor) == OH_Rdb_ErrCode::RDB_OK) {
        cursor->getInt64(cursor, 0, &user.id);
        cursor->getText(cursor, 1, user.name, sizeof(user.name));
        cursor->getInt64(cursor, 2, &user.age);
        users.push_back(user);
    }
    // 释放谓词实例
    predicates->destroy(predicates);
    // 释放结果集
    cursor->destroy(cursor);
    return users;
}